package com.hs.sfzy.controller;

import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*") // 开发环境使用，生产环境需指定具体域名
public class AIController {

    // 建议从配置文件读取，而非硬编码
    private final String apiKey = "41ea934a-6618-45db-8b5b-de775ec033ab";
    // 确认火山引擎的有效模型ID
    private final String modelId = "doubao-seed-1-6-250615"; // 示例模型ID，需替换为实际可用的
    // 指定API地区（根据你的API密钥地区设置）
    private final String region = "cn-henan";

    @PostMapping("/chat")
    public Map<String, Object> chat(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 1. 验证输入
            String userMessageContent = (String) request.get("message");
            if (userMessageContent == null || userMessageContent.trim().isEmpty()) {
                response.put("success", false);
                response.put("error", "消息内容不能为空");
                return response;
            }

            // 2. 初始化服务（指定地区）
            ArkService arkService = ArkService.builder().apiKey(apiKey).region(region) // 添加地区配置
                    .build();

            // 3. 构建消息列表
            List<ChatMessage> chatMessages = new ArrayList<>();
            chatMessages.add(ChatMessage.builder().role(ChatMessageRole.USER).content(userMessageContent).build());

            // 4. 构建请求
            ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder().model(modelId).messages(chatMessages).build();

            // 5. 调用API（移除不必要的类型转换）
            String aiResponse = (String) arkService.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage().getContent(); // 假设getContent()本身返回String

            // 6. 返回成功响应
            response.put("success", true);
            response.put("reply", aiResponse);

            // 7. 关闭服务
            arkService.shutdownExecutor();

        } catch (Exception e) {
            // 详细错误信息便于调试
            response.put("success", false);
            response.put("error", "AI请求失败: " + e.getMessage());
            e.printStackTrace();
        }

        return response;
    }
}
